package com.ghy.ic.mo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ghy.ic.mo.dao.JbModuleQyCodeUrl;
import com.ghy.ic.mo.dao.MmsRyxx;
import com.ghy.ic.mo.domain.bo.User;
import com.google.common.base.Strings;
import com.jfinal.json.FastJson;
import com.jfinal.kit.PropKit;
import com.jfinal.qyweixin.sdk.api.ApiConfig;
import com.jfinal.qyweixin.sdk.api.ApiResult;
import com.jfinal.qyweixin.sdk.api.ConUserApi;
import com.jfinal.qyweixin.sdk.api.OAuthApi;
import com.jfinal.qyweixin.sdk.jfinal.ApiController;
import com.jfinal.weixin.sdk.api.UserApi;
import org.apache.log4j.Logger;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import static com.ghy.ic.mo.constant.BcsConstant.MODULES;
import static com.ghy.ic.mo.constant.BcsConstant.NUMBER_OF_ATTEMPTS;

/**
 * @author Y-Tree
 * @date 18-12-1 下午10:49
 */
public class QyOauthController extends ApiController {

    private static final Logger LOGGER = Logger. getLogger(QyOauthController.class);

    private static final String CORP_ID = "corpId";
    private static final String USER = "user";
    private static final String CODE = "code";
    private static final String STATE = "state";
    private static final String DEVICE_ID = "DeviceId";
    private static final String OPEN_ID = "OpenId";

    /**
     * 用户验证接口
     */
    public void index(){

        LOGGER.info("Oauth 接口程序执行。。。");
        String url = "http://" + getRequest().getServerName() + getRequest().getContextPath() + getRequest().getServletPath();
        LOGGER.info("我的url是 : " + url);

        try {
            String redirectUri = URLEncoder.encode(url + "/code", "utf-8");
            String codeUrl = OAuthApi.getCodeUrl(redirectUri, PropKit.get(CORP_ID), true);
            LOGGER.info("codeUrl : " + codeUrl);
            // 将获取的codeUrl 存入数据库， 当session失效时，
            // 就从库中获取回调链接，跳转到链接，重新获取用户信息
            // 查看是否存在记录
            JbModuleQyCodeUrl allByModule = JbModuleQyCodeUrl.getAllByModule(MODULES);
            if (allByModule == null){
                // 尝试三次
                for(int i = 0; i < NUMBER_OF_ATTEMPTS; i++){
                    if (JbModuleQyCodeUrl.add(MODULES, codeUrl)){
                        break;
                    }
                }

            }else {
                // 尝试三次
                for(int i = 0; i < NUMBER_OF_ATTEMPTS; i++){
                    if (JbModuleQyCodeUrl.update(allByModule.getId(), codeUrl)){
                        break;
                    }
                }
            }

            redirect(codeUrl);
        } catch (UnsupportedEncodingException e) {
            LOGGER.info(e);
        }
    }

    /**
     * redirect_uri 通过企业微信验证后的回调方法
     */
    public void code(){

        getUserInfoByCode();
        User user = getSessionAttr(USER);
        renderJson(user);
        redirect("/index.html");

    }

    /**
     * 根据code获取用户详情
     */
    private void getUserInfoByCode(){
        String userId = null;
        String deviceId = null;
        String openid = null;

        // code 为空直接返回不执行， 否则就执行下面的根据code获取用户信息代码
        if(isParaBlank(CODE)){
            return ;
        }

        String code = getPara(CODE);
        LOGGER.info("code:"+code);

        if (!isParaBlank(STATE)) {

            String state = getPara(STATE);
            LOGGER.info(" state:"+state);
        }

        ApiResult userInfoApiResult = OAuthApi.getUserInfoByCode(code);
        LOGGER.info(userInfoApiResult.toString());

        if (userInfoApiResult.isSucceed()) {
            String userInfoJson = userInfoApiResult.getJson();
            JSONObject object = JSON.parseObject(userInfoJson);
            deviceId = object.getString(DEVICE_ID);
            LOGGER.info("deviceId : " + deviceId);

            // test 根据openid获取用户基本信息
            if(null != object.getString(OPEN_ID)){
                object.getString(OPEN_ID);
                LOGGER.info(UserApi.getUserInfo(object.getString(OPEN_ID)));
            }

            try {
                //如果获取userId为空 说明没有关注
                userId = object.getString("UserId");
                LOGGER.info("UserId 333333333333333333333333333 : " + userId);
                /*userId!=null && !userId.equals("")*/
                if (Strings.isNullOrEmpty(userId)) {
                    ApiResult toOpenIdApiResult =
                            OAuthApi.ToOpenId("{\"userid\":\""+userId+"\",\"agentid\":0}");
                    if (toOpenIdApiResult.isSucceed()) {
                        openid = JSON.parseObject(toOpenIdApiResult.getJson()).getString("openid");
                        LOGGER.info("openid : "+openid);
                    }
                }else {
                    openid = object.getString(OPEN_ID);
                    //如果未关注 openid无法转化为userid
                    String json="{\"openid\":\""+openid+"\"}";
                    ApiResult toUserIdApiResult = OAuthApi.ToUserId(json);
                    if (toUserIdApiResult.isSucceed()) {
                        userId = JSON.parseObject(toUserIdApiResult.getJson()).getString("userid");
                        LOGGER.info("userId : "+userId);
                    }
                }
            } catch (Exception e) {
                LOGGER.info(e);
            }
        }
        setAttr("openID", "userId:"+userId+" deviceId:"+deviceId+" openid:"+openid);
        LOGGER.info("userId:"+userId+" deviceId:"+deviceId+" openid:"+openid);

        //获取用户的详细信息 并将其保存到数据库中
        setSessionAttr("userId", userId);
        ApiResult userInfo = ConUserApi.getUser((String)getSessionAttr("userId"));
        User user = FastJson.getJson().parse(userInfo.getJson(), User.class);
        LOGGER.info("user : " + user.toString());
        setSessionAttr(USER, user);

        // 存入用户信息之前，先查询数据库中是否已经存在该用户，如果存在则更新
        MmsRyxx userInfoByUserId = MmsRyxx.getUserInfoByUserId(user.getUserid());
        if(null == userInfoByUserId){
            if(MmsRyxx.add(user.getUserid(), user.getName(),
                    user.getGender(), user.getMobile(),user.getAvatar())){
                LOGGER.info("user info 存储成功！");
            }else {
                LOGGER.error("user info 存储失败！");
            }
        }else {
            if(MmsRyxx.update(userInfoByUserId.getXh(),
                    user.getUserid(),user.getName(), user.getGender(),
                    user.getMobile(),  user.getAvatar())){
                LOGGER.info("user info 更新成功！");
            }else {
                LOGGER.error("user info 更新失败！");
            }
        }
    }

}
